'use client'

import { useState } from 'react'
import { trpc } from '@/lib/trpc-provider'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Copy, RotateCcw, Upload, Download } from 'lucide-react'
import { toast } from 'sonner'

export default function UrlEncoderPage() {
  const [input, setInput] = useState('')
  const [output, setOutput] = useState('')
  const [mode, setMode] = useState<'encode' | 'decode'>('encode')
  const [type, setType] = useState<'component' | 'full'>('component')

  const encodeUrl = trpc.tools.encodeUrl.useMutation({
    onSuccess: (data) => {
      if (data.success && data.result) {
        setOutput(data.result)
      } else {
        toast.error(data.error || 'URL编码失败')
      }
    },
    onError: (error) => {
      toast.error(error.message || 'URL编码失败')
    }
  })

  const decodeUrl = trpc.tools.decodeUrl.useMutation({
    onSuccess: (data) => {
      if (data.success && data.result) {
        setOutput(data.result)
      } else {
        toast.error(data.error || 'URL解码失败')
      }
    },
    onError: (error) => {
      toast.error(error.message || 'URL解码失败')
    }
  })

  const handleProcess = () => {
    if (!input.trim()) {
      toast.error('请输入要处理的文本')
      return
    }

    if (mode === 'encode') {
      encodeUrl.mutate({ text: input, type })
    } else {
      decodeUrl.mutate({ text: input, type })
    }
  }

  const handleCopy = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text)
      toast.success('已复制到剪贴板')
    } catch (error) {
      toast.error('复制失败')
    }
  }

  const handleClear = () => {
    setInput('')
    setOutput('')
  }

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const content = e.target?.result as string
        setInput(content)
      }
      reader.readAsText(file)
    }
  }

  const handleDownload = () => {
    if (!output) {
      toast.error('没有可下载的内容')
      return
    }

    const blob = new Blob([output], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `url-${mode}d.txt`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    toast.success('文件已下载')
  }

  const examples = [
    {
      title: 'URL组件编码',
      input: 'Hello World!',
      output: 'Hello%20World!',
      type: 'component' as const
    },
    {
      title: '完整URL编码',
      input: 'https://example.com/search?q=hello world',
      output: 'https://example.com/search?q=hello%20world',
      type: 'full' as const
    },
    {
      title: '中文字符编码',
      input: '你好世界',
      output: '%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C',
      type: 'component' as const
    }
  ]

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="max-w-4xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-bold mb-2">URL编码工具</h1>
          <p className="text-muted-foreground">
            对URL进行编码和解码，支持组件编码和完整URL编码
          </p>
        </div>

        <div className="grid gap-6">
          {/* 模式选择 */}
          <Card>
            <CardHeader>
              <CardTitle>处理模式</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label className="text-base font-medium mb-3 block">操作类型</Label>
                  <RadioGroup value={mode} onValueChange={(value) => setMode(value as 'encode' | 'decode')}>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="encode" id="encode" />
                      <Label htmlFor="encode">编码 (Encode)</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="decode" id="decode" />
                      <Label htmlFor="decode">解码 (Decode)</Label>
                    </div>
                  </RadioGroup>
                </div>
                <div>
                  <Label className="text-base font-medium mb-3 block">编码类型</Label>
                  <RadioGroup value={type} onValueChange={(value) => setType(value as 'component' | 'full')}>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="component" id="component" />
                      <Label htmlFor="component">组件编码 (encodeURIComponent)</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="full" id="full" />
                      <Label htmlFor="full">完整URL编码 (encodeURI)</Label>
                    </div>
                  </RadioGroup>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 输入区域 */}
          <Card>
            <CardHeader>
              <CardTitle>输入文本</CardTitle>
              <CardDescription>
                输入需要{mode === 'encode' ? '编码' : '解码'}的文本
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <Textarea
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  placeholder={`请输入要${mode === 'encode' ? '编码' : '解码'}的文本...`}
                  className="min-h-[120px] font-mono"
                />
                <div className="flex flex-wrap gap-2">
                  <Button
                    onClick={handleProcess}
                    disabled={encodeUrl.isPending || decodeUrl.isPending}
                    className="flex-1 sm:flex-none"
                  >
                    {mode === 'encode' ? '编码' : '解码'}
                  </Button>
                  <Button variant="outline" onClick={handleClear}>
                    <RotateCcw className="w-4 h-4 mr-2" />
                    清空
                  </Button>
                  <div className="relative">
                    <input
                      type="file"
                      accept=".txt,.json,.xml,.html,.css,.js,.ts"
                      onChange={handleFileUpload}
                      className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                    />
                    <Button variant="outline">
                      <Upload className="w-4 h-4 mr-2" />
                      上传文件
                    </Button>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 输出区域 */}
          <Card>
            <CardHeader>
              <CardTitle>输出结果</CardTitle>
              <CardDescription>
                {mode === 'encode' ? '编码' : '解码'}后的结果
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <Textarea
                  value={output}
                  readOnly
                  placeholder="处理结果将显示在这里..."
                  className="min-h-[120px] font-mono bg-muted"
                />
                <div className="flex flex-wrap gap-2">
                  <Button
                    variant="outline"
                    onClick={() => handleCopy(output)}
                    disabled={!output}
                  >
                    <Copy className="w-4 h-4 mr-2" />
                    复制结果
                  </Button>
                  <Button
                    variant="outline"
                    onClick={handleDownload}
                    disabled={!output}
                  >
                    <Download className="w-4 h-4 mr-2" />
                    下载文件
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 示例 */}
          <Card>
            <CardHeader>
              <CardTitle>使用示例</CardTitle>
              <CardDescription>
                点击示例可快速填入输入框
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-4">
                {examples.map((example, index) => (
                  <div
                    key={index}
                    className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
                    onClick={() => {
                      setInput(example.input)
                      setType(example.type)
                      setMode('encode')
                    }}
                  >
                    <h4 className="font-medium mb-2">{example.title}</h4>
                    <div className="space-y-2 text-sm">
                      <div>
                        <span className="text-muted-foreground">输入: </span>
                        <code className="bg-muted px-1 py-0.5 rounded">{example.input}</code>
                      </div>
                      <div>
                        <span className="text-muted-foreground">输出: </span>
                        <code className="bg-muted px-1 py-0.5 rounded">{example.output}</code>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* 说明 */}
          <Card>
            <CardHeader>
              <CardTitle>使用说明</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4 text-sm">
                <div>
                  <h4 className="font-medium mb-2">编码类型说明：</h4>
                  <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                    <li><strong>组件编码 (encodeURIComponent)</strong>: 编码所有特殊字符，适用于URL参数值</li>
                    <li><strong>完整URL编码 (encodeURI)</strong>: 保留URL结构字符，适用于完整URL</li>
                  </ul>
                </div>
                <div>
                  <h4 className="font-medium mb-2">常见用途：</h4>
                  <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                    <li>处理URL参数中的特殊字符</li>
                    <li>编码中文字符用于URL传输</li>
                    <li>解码接收到的URL编码数据</li>
                    <li>处理表单数据的URL编码</li>
                  </ul>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}